package com.wenhai.spring.bean.definition;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;

/**
 * @Author:wenhai
 * @Description: {@link org.springframework.beans.factory.config.BeanDefinition} 构建
 * @Date:2020/3/6
 */
public class BeanDefinitionCreationDemo {
    public static void main(String[] args) {

        // 1.  通过BeanDefinitionBuilder构建
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        // 1.1 通过属性设置
        beanDefinitionBuilder.addPropertyValue("id", 3L);
        beanDefinitionBuilder.addPropertyValue("username", "谢文海");
        // 1.2 获取BeanDefinition实例
        BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();

        // 2.  通过AbstractBeanDefinition派生构建
        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        // 2.1 设置Bean类型
        genericBeanDefinition.setBeanClass(User.class);
        // 2.2 设置属性值
        MutablePropertyValues propertyValues = new MutablePropertyValues();
//        propertyValues.addPropertyValue("id", 4L);
//        propertyValues.addPropertyValue("username", "谢文海");
        propertyValues.add("id", 4L).add("username", "谢文海");
        genericBeanDefinition.setPropertyValues(propertyValues);

        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        beanFactory.registerBeanDefinition("user", beanDefinition);
        beanFactory.registerBeanDefinition("user1", genericBeanDefinition);
        System.out.println(beanFactory.getBean("user"));
        System.out.println(beanFactory.getBean("user1"));

    }
}
